/*
	This file is part of AVRCppLib.

    AVRCppLib is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AVRCppLib is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AVRCppLib.  If not, see <http://www.gnu.org/licenses/>.

    Copyright (C) Maxime Lemonnier 2007-2011
 */

char * strdup(const prog_mem * string, Allocator allocator)
{
	char * dup = new(allocator) char[strlen(string) + 1];

	return strcpy(dup, string);
}

char * strdup(const char * string, Allocator allocator)
{
	char * dup = new(allocator) char[strlen(string) + 1];

	return strcpy(dup, string);
}

char * strdupn(const char * string, size_t maxLenght, Allocator allocator)
{
	char * dup = new(allocator) char[strnlen(string, maxLenght) + 1];

	return strcpy(dup, string);
}

char * strdup(void * memoryToRealloc, const prog_mem * string)
{
	//TODO fix this workaround when realloc is repaired
	char * dup = new(memoryToRealloc) char[strlen(string) + 1];
//	delete memoryToRealloc;
//	char * dup = new char[strlen(string) + 1];
	return strcpy(dup, string);
}

template <typename UnsignedIntType>
UnsignedIntType strToUnsignedInt(const char * string)
{
	UnsignedIntType number = 0;

	size_t strLenght = strlen(string);

	for(size_t index = 0; index < strLenght; index++)
	{
		number += pow(10, index) * (string[strLenght - 1 - index] - '0');
//		fprintf(stderr, "10^%u * %u, char is %c number is %u \n\r", index, (string[strLenght - 1 - index] - '0'), string[strLenght - 1 - index], number);
	}

	return number;
}

template<typename ValueType, typename SumType>
SumType computeChecksum(ValueType * array, size_t size)
{
	return checksum(sum<ValueType, SumType>(array, size));
}

template<typename SumType>
SumType checksum(SumType sum)
{
	return ~sum + 1;
}

template<typename ValueType, typename SumType>
SumType sum(ValueType * array, size_t size)
{
	SumType overflowingSum = 0;
	for(size_t i = 0; i < size; i++)
		overflowingSum += array[i];

	return overflowingSum;
}

